package tablefilter;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;

public class FilteredColumnHeader extends HBox{
	
	private final BooleanProperty isFiltered = new SimpleBooleanProperty(false);
	private final Image isFilteredIcon = new Image("filtered.png");
	private final Image isNotFilteredIcon = new Image("not_filtered.png");
	private final ImageView buttonIcon = new ImageView();

	private Label label;
	private Button filterButton;

	public <S, T> FilteredColumnHeader(TableColumn<S, T> column) {
		super();
		if (column.isSortable())setPadding(new Insets(0, 20, 0, 0));
		this.setAlignment(Pos.CENTER);
		this.getStyleClass().add("filteredColumnHeader");
		this.label = new Label();
		label.textProperty().bind(column.textProperty());
		this.label.setMaxWidth(Double.MAX_VALUE);
		this.label.setAlignment(Pos.CENTER);
		HBox.setHgrow(this.label, Priority.ALWAYS);
		this.filterButton = buildFilterButton();
		this.getChildren().addAll(this.label, filterButton);
		
		buttonIcon.setImage(isNotFilteredIcon);
		isFiltered.addListener(new ChangeListener<Boolean>() {
			@Override
			public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
				if (newValue) {
					buttonIcon.setImage(isFilteredIcon);
				} else {
					buttonIcon.setImage(isNotFilteredIcon);
				}
			}
		});
	}
	
	private Button buildFilterButton() {
		Button filterButton = new Button();
		filterButton.setGraphic(buttonIcon);
		filterButton.setFocusTraversable(false);
		buttonIcon.getStyleClass().add("filterIcon");
		filterButton.getStyleClass().add("filterButton");
		return filterButton;
	}
	
	public Label getLabel() {
		return label;
	}

	public Button getFilterButton() {
		return filterButton;
	}

	public final BooleanProperty isFilteredProperty() {
		return this.isFiltered;
	}

	public final boolean isIsFiltered() {
		return this.isFilteredProperty().get();
	}

	public final void setIsFiltered(final boolean isFiltered) {
		this.isFilteredProperty().set(isFiltered);
	}

}
